<?php

namespace App\Http\Controllers;

use App\Http\Requests\SubjectCreate;
use App\Http\Requests\SubjectUpdate;
use App\Models\Subject;
use Illuminate\Http\Request;

class SubjectController extends Controller
{
    public function create(SubjectCreate $request){

        $subject = $request->validated();

        $subject['school_id'] = $request->school_id;
        $subject['campus_id'] = $request->campus_id;

        try{
            $res = Subject::create($subject);
            return resSucc($res, "创建成功");
        } catch (\Exception $e) {
            return resFail($e, "创建失败");
        } catch (\Throwable $e) {
            return resFail($e, "创建失败");
        }
    }

    public function update(SubjectUpdate $request){

        $subject = $request->validated();

        try{
            $res = Subject::where('id', $subject['id'])->update($subject);
            return resSucc($res, "更新成功");
        } catch (\Exception $e) {
            return resFail($e, "更新失败");
        } catch (\Throwable $e) {
            return resFail($e, "更新失败");
        }
    }

    public function list(Request $request){
        $limit = $request->limit ?? 10;
        $res = Subject::where([
            'school_id' => $request->school_id,
            'campus_id' => $request->campus_id
        ])->paginate($limit);
        return resSucc(formatPage($res), "课程列表");
    }
}
